package com.example.exp_4_javaweb;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

@WebServlet("/login")

public class Login extends HelloServlet{

    static Connection conn = null;
    static Statement st = null;
    static PreparedStatement ps = null;
    static ResultSet rs= null;

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        Student student = new Student();
        student.setName(request.getParameter("name"));
        student.setPassword(request.getParameter("password"));

        request.setAttribute("student",student);
        request.setAttribute("isAccountRight",isAccountRight(student));

        request.getRequestDispatcher("loginresult").forward(request,response);
    }

    public boolean isAccountRight(Student student) {
        try {
            conn = DBConnection.getConnection();
            String sql = "select id from test.student where name = ? and password = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, student.getName());
            ps.setString(2, student.getPassword());
            rs = ps.executeQuery();
            return rs.next();
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        } finally {
            DBConnection.close(rs,ps,conn);
        }
    }
}
